package com.eight.paper.admin.util;

import com.deepoove.poi.data.*;
import com.eight.common.config.EightConfig;
import com.eight.common.constant.ExamConstants;
import com.eight.common.utils.StringUtils;
import com.eight.paper.admin.domain.model.QuestionTemplate;
import com.eight.paper.admin.domain.model.enums.ImportQuestionTypeEnum;
import com.eight.paper.admin.domain.model.enums.QuestionTypeEnum;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 试题导出word处理
 */
public class PoitlUtil {

    /**
     * 输出单个试题
     * @param of
     * @param questionList
     * @param questionNo 导出试题序号
     * @param importQuestionType
     * @param showScoreAndExamineeAnswer 是否显示考生分值和答题结果
     * @param showAnswer 是否显示答案
     * @return
     */
    public static Map<String, Object> createQuestion(Documents.DocumentBuilder of, List<QuestionTemplate> questionList, AtomicInteger questionNo, ImportQuestionTypeEnum importQuestionType, Boolean showScoreAndExamineeAnswer, Boolean showAnswer) {
        Map<String, Object> dataAll = new HashMap<>();
        if (CollectionUtils.isNotEmpty(questionList)) {
            BigDecimal score = BigDecimal.ZERO;
            boolean addScore = false;
            String questionType = "";
            String answer = "";
            Integer correct = 0;
            for (int i = 0; i < questionList.size(); i++) {
                 questionType = questionList.get(0).getQuestionType();
                if (StringUtils.isNotBlank(questionType)) {
                    questionType = questionType.toUpperCase();
                }
                QuestionTemplate question = questionList.get(i);
                //处理题目内容
                if (i == 0) {
                    if (i != 0 && addScore) {
                        //插入考生分值
                        if (showScoreAndExamineeAnswer) {
                            of.addParagraph(Paragraphs.of("得分：" + score).create());
                        }
                        addScore = false;
                    }
                    Map<String, Object> datas = createTitle(of,question,questionNo,importQuestionType,questionType,showScoreAndExamineeAnswer,showAnswer);
                    dataAll.putAll(datas);
                    if (showScoreAndExamineeAnswer) {
                        score = question.getExamineeScore();
                        score = score == null ? BigDecimal.ZERO : score;
                        answer = question.getAnswer();
                        correct = question.getCorrect();
                        addScore = true;
                    }
                } else {
                    createOptions(of,question,questionType,showScoreAndExamineeAnswer,showAnswer);
                }
            }
            if (addScore) {
                //插入考生分值
                if (showScoreAndExamineeAnswer) {
                    String result = correct==1?"正确":"错误";
                    String bottomInfo = String.format("得分：%s，结果：%s",score,result);
                    if(questionType.equals(QuestionTypeEnum.SingleChoice.getName())||questionType.equals(QuestionTypeEnum.SingleChoice.getName())||questionType.equals(QuestionTypeEnum.TrueFalse.getName())){
                        bottomInfo = String.format("得分：%s，答案: %s，结果：%s",score,answer,result);
                    }
                    of.addParagraph(Paragraphs.of(Texts.of(bottomInfo).bold().create()).create());
                }
            }
            of.addParagraph(Paragraphs.of("").create());
        }
        return dataAll;
    }

    /**
     * 考试顶部header
     *
     * @param
     */
    public static Map<String, Object> createHeader(Documents.DocumentBuilder of, List<Integer> questionTypes) {
        Map<String, Object> dataAll = new HashMap<>();
        of.addParagraph(Paragraphs.of(Texts.of("{{paperName}}").bold().fontSize(18).create()).center().create());
        String[] questionTypeNames = ExamConstants.QUESTIONTYPE_NAMES.split(";");
        List<String> listRow0 = Lists.newArrayList();
        List<String> listRow1 = Lists.newArrayList();
        if (questionTypes.size() > 0) {
            listRow0.add("题型");
            listRow1.add("每项\n得分");
            for (Integer i : questionTypes) {
                listRow0.add(questionTypeNames[i]);
                listRow1.add("{{varQuestion_" + i + "}}");
            }
            listRow0.add("总分");
            listRow1.add("{{totalScore}}");
        }

        RowRenderData row0 = Rows.of(listRow0.toArray(new String[0])).center().create();
        RowRenderData row1 = Rows.of(listRow1.toArray(new String[0])).center().create();

        of.addParagraph(Paragraphs.of(Texts.of("{{examineeInfo}}").bold().create()).create());
        //屏蔽试题分类统计
        //of.addTable(Tables.create(row0, row1));
        of.addParagraph(Paragraphs.of("").create());
        return dataAll;
    }

    /**
     * 创建试卷大题信息
     * @param of
     * @param groupInfo
     */
    public static void createGroupInfo(Documents.DocumentBuilder of, String groupInfo) {
        of.addParagraph(Paragraphs.of(Texts.of(groupInfo).bold().fontSize(12).create()).create());
    }

    /**
     * 生成题干内容
     *
     * @param of
     * @param question
     * @param importQuestionType
     */
    public static Map<String, Object> createTitle(Documents.DocumentBuilder of, QuestionTemplate question, AtomicInteger questionNo,ImportQuestionTypeEnum importQuestionType,String questionType, Boolean showScoreAndExamineeAnswer,Boolean showAnswer) {
        Map<String, Object> datas = new HashMap<>();
        String content = question.getTitle();
        String answer = "";
        int m = 0;
        List<String> imgs = matcherImgs(content);
        content = StringEscapeUtils.unescapeJava(content);
        for (String img : imgs) {
            String src = matcherImgSrc(img);
            if (StringUtils.isNotBlank(src)) {
                String imgInfo = StringEscapeUtils.unescapeJava(img);
                String varNo = questionNo + "_" + m;
                String var = String.format("var%s", varNo);
                String varRender = String.format("{{@%s}}", var);
                content = content.replaceFirst(imgInfo, varRender);
                String localPath = EightConfig.getProfile();
                String frontProfile = EightConfig.getFrontProfile();
                src = src.replaceAll(frontProfile, localPath);
                datas.put(var, Pictures.ofLocal(src).size(20, 20).create());
                m++;
            }
        }

        String questionScore = question.getScore() == null ? "无分值" : question.getScore() + "分";
        content = content.replace("%", "%%");
        QuestionTypeEnum questionTypeEnum = QuestionTypeEnum.fromName(questionType);
        if(QuestionUtil.checkQuestionType(questionTypeEnum.getCode())) {
            if(QuestionTypeEnum.B1==questionTypeEnum){
                if (importQuestionType == ImportQuestionTypeEnum.试题) {
                    content = String.format("%s、（%s）\n" + "%s、"+content, questionNo.incrementAndGet(), questionType, question.getAnswer());
                } else if (showScoreAndExamineeAnswer && importQuestionType == ImportQuestionTypeEnum.试卷) {
                    content = String.format("%s、（%s，%s）\n" + "%s、"+content, questionNo.incrementAndGet(), questionType, questionScore, question.getAnswer());
                } else {
                    content = String.format("%s、（%s，%s）\n" + "%s、"+content, questionNo.incrementAndGet(), questionType, questionScore, question.getAnswer());
                }
            }else if(QuestionTypeEnum.A3A4Single==questionTypeEnum||QuestionTypeEnum.A3A4Single==questionTypeEnum){
                if (importQuestionType == ImportQuestionTypeEnum.试题) {
                    content = String.format("%s、（%s）" + content, questionNo.incrementAndGet(), questionType);
                } else if (showScoreAndExamineeAnswer && importQuestionType == ImportQuestionTypeEnum.试卷) {
                    content = String.format("%s、（%s，%s）" + content, questionNo.incrementAndGet(), questionType, questionScore);
                } else {
                    content = String.format("%s、（%s，%s）" + content, questionNo.incrementAndGet(), questionType, questionScore);
                }
            }else {
                if(showAnswer) {
                    answer = StringUtils.isBlank(question.getAnswer()) ? "" : question.getAnswer().trim();
                }
                if (importQuestionType == ImportQuestionTypeEnum.试题) {
                    content = String.format("%s、（%s）" + content + "（ %s ）", questionNo.incrementAndGet(), questionType, answer);
                } else if (showScoreAndExamineeAnswer && importQuestionType == ImportQuestionTypeEnum.试卷) {
                    content = String.format("%s、（%s，%s）" + content + "（    %s    ）", questionNo.incrementAndGet(), questionType, questionScore, question.getExamineeAnswer());
                } else {
                    content = String.format("%s、（%s，%s）" + content + "（    %s    ）", questionNo.incrementAndGet(), questionType, questionScore, answer);
                }
            }
            content = delHTMLTag(content);
            of.addParagraph(Paragraphs.of(content).create());
        }else  {
            if (importQuestionType==ImportQuestionTypeEnum.试题) {
                content = String.format("%s、（%s）" + content, questionNo.incrementAndGet(), questionType);
            } else if (importQuestionType==ImportQuestionTypeEnum.试卷) {
                content = String.format("%s、（%s，%s）" + content, questionNo.incrementAndGet(), questionType, questionScore);
                if(showScoreAndExamineeAnswer) {
                    answer = StringUtils.isBlank(question.getAnswer()) ? "" : question.getAnswer().trim();
                    answer = "考生答案：" + answer;
                    answer = delHTMLTag(answer);
                }else {
                    if(showAnswer){
                        answer = StringUtils.isBlank(question.getAnswer()) ? "" : question.getAnswer().trim();
                        answer = "参考答案：\n" + answer;
                        answer = delHTMLTag(answer);
                    }else {
                        if ("名词解释".contains(questionType)) {
                            answer = "\n\n";
                        } else if ("问答题,病例分析题,论述题".contains(questionType)) {
                            answer = "\n\n\n\n\n\n\n\n\n";
                        }
                    }
                }
            }
            content = delHTMLTag(content);
            of.addParagraph(Paragraphs.of(content).create());
            of.addParagraph(Paragraphs.of(answer).create());
        }
        return datas;
    }

    /**
     * 生成题目内容
     *
     * @param of
     * @param question
     */
    public static void createOptions(Documents.DocumentBuilder of, QuestionTemplate question,String questionType, Boolean showScoreAndExamineeAnswer, Boolean showAnswer) {
        QuestionTypeEnum questionTypeEnum = QuestionTypeEnum.fromName(questionType);
        if(QuestionUtil.checkQuestionType(questionTypeEnum.getCode())) {
            String content = question.getAnswer() + "、" + question.getTitle();
            //B1、A3A4小题题干
            if(StringUtils.isNotBlank(question.getQuestionType())){
                String answer = "  ";
                if(showAnswer){
                    answer = StringUtils.isBlank(question.getAnswer()) ? "  " : question.getAnswer().trim();
                }
                content = String.format("（%s）、%s（%s）",question.getQuestionType(),question.getTitle(),answer);
                if(showScoreAndExamineeAnswer){
                    String examineeAnswer = StringUtils.isBlank(question.getExamineeAnswer())?"  ":question.getExamineeAnswer().trim();
                    content = String.format("（%s）、%s（%s）\n得分：%s 答案：%s(分值：%s)",question.getQuestionType(),question.getTitle(),examineeAnswer,question.getExamineeScore(),answer,question.getScore());
                }
            }
            of.addParagraph(Paragraphs.of(content).create());
        }else {
            if(showAnswer) {
                String content = String.format("%s、%s(分值：%s)",question.getTitle(),question.getAnswer(),question.getScore());
                if(showScoreAndExamineeAnswer){
                    content = String.format("%s、%s\n得分：%s 答案：%s(分值：%s)",question.getTitle(),question.getExamineeAnswer(),question.getExamineeScore(),question.getAnswer(),question.getScore());
                }
                of.addParagraph(Paragraphs.of(content).create());
            }
        }
    }

    /**
     * 去除富文本编辑器标签
     *
     * @param htmlStr
     * @return
     **/
    public static String delHTMLTag(String htmlStr) {
        String script = "<script[^>]*?>[\\s\\S]*?<\\/script>";
        String style = "<style[^>]*?>[\\s\\S]*?<\\/style>";
        String html = "<[^>]+>";
        String space = "(\r?\n(\\s*\r?\n)+)";
        String white = "&nbsp;";
        Pattern pScript = Pattern.compile(script, 2);
        Matcher mScript = pScript.matcher(htmlStr);
        htmlStr = mScript.replaceAll("");
        Pattern pStyle = Pattern.compile(style, 2);
        Matcher mStyle = pStyle.matcher(htmlStr);
        htmlStr = mStyle.replaceAll("");
        Pattern pHtml = Pattern.compile(html, 2);
        Matcher mHtml = pHtml.matcher(htmlStr);
        htmlStr = mHtml.replaceAll("");
        Pattern pSpace = Pattern.compile(space, 2);
        Matcher mSpace = pSpace.matcher(htmlStr);
        htmlStr = mSpace.replaceAll("");
        htmlStr = htmlStr.replaceAll(white, "");
        return htmlStr.trim();
    }

    /**
     * 获取内容中的图片地址
     *
     * @param content
     * @return list
     */
    public static List<String> matcherImgs(String content) {
        List<String> srcList = new ArrayList<>();
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        if (hasPic)
        {
            while (hasPic)
            {
                String group = matcher.group(0);
                srcList.add(group);
                hasPic = matcher.find();
            }
        }
        return srcList;
    }

    /**
     * 匹配图片的地址
     * @param img
     * @return
     */
    public static String matcherImgSrc(String img) {
        Pattern srcText = Pattern.compile("(src|SRC)=\"(.*?)\"");
        Matcher matcher = srcText.matcher(img);
        if (matcher.find()) {
            return matcher.group(2);
        } else {
            return "";
        }
    }
}
